<template>
  <!-- PAGE CONTENT BEGINS -->
  <div>
    <p>
      <button v-on:click="add()" class="btn btn-white btn-warning btn-round">
        <i class="ace-icon fa fa-edit bigger-120 blue"></i>
        新增
      </button>
      &nbsp;
      <button v-on:click="list(1)" class="btn btn-white btn-warning btn-round">
        <i class="ace-icon fa fa-refresh bigger-120 blue"></i>
        刷新
      </button>
    </p>
    <pagination ref="pagination" v-bind:list="list"></pagination>

    <div class="row">
      <div v-for="course in courses" :key="course.num" class="col-md-4">
        <div class="thumbnail search-thumbnail">
          <div v-show="course.charge=='F'">
            <span class="search-promotion label label-success arrowed-in arrowed-in-right">
              {{COURSE_CHARGE | optionKV(course.charge)}}
            </span>
          </div>
          <div v-show="course.charge=='C'">
            <span class="search-promotion label label-primary arrowed-in arrowed-in-right">
              {{COURSE_CHARGE | optionKV(course.charge)}}
            </span>
          </div>
          <img v-show="!course.image" class="media-object" src="/static/image/base2.jpg" />
          <img v-show="course.image" class="media-object" v-bind:src=course.image />
          <div class="caption">
            <div class="clearfix">
              <span class="pull-right label label-pink info-label">
                {{COURSE_LEVEL | optionKV(course.level)}}
              </span>
              <span class="pull-right label label-purple info-label">
                {{ COURSE_STATUS | optionKV(course.status) }}
              </span>
              &nbsp;
              <span class="pull-right label label-grey info-label">
                {{ course.time | formatSecond }}
              </span>
              &nbsp;
              <span class="pull-right label label-important info-label">
                {{ course.enroll }}人已参与
              </span>
              &nbsp;
              <span class="pull-right label label-holder info-label">
                {{ course.sort }}
              </span>
            </div>

            <h3 class="search-title">
              <a href="#" class="blue">{{course.name}}</a>&nbsp;
              <div v-show="course.charge=='F'">
                <small>
                  <s class="red">原价{{ course.price }}</s>
                </small>
                <b class="green">￥00.00</b>
              </div>
              <div v-show="course.charge=='C'">
                <span class="label label-success arrowed-in arrowed-in-right">热卖中</span>
                <b class="green">￥{{ course.price }}</b>
              </div>
            </h3>

            <div v-for="teacher in teachers.filter(t=>{return t.id===course.teacherId})"
                 class="profile-activity clearfix" :key="teacher.num">
              <div>
                <img v-show="!teacher.image" class="pull-left" src="/static/image/teacherbase.jpg">
                <img v-show="teacher.image" class="pull-left" v-bind:src=teacher.image>
                <a class="user" href="#">讲师：{{ teacher.name }}</a>
                <br>
                职称：{{ teacher.position }}
              </div>
            </div>

            <p> {{ course.summary }}</p>
            <p>
              <button v-on:click="toChapter(course)" class="btn btn-xs btn-primary">
                <i class="ace-icon fa fa-table bigger-120"></i>大章
              </button>&nbsp;&nbsp;&nbsp;
              <button v-on:click="toContent(course)" class="btn btn-xs btn-primary">
                <i class="ace-icon fa fa-file-text bigger-120"></i>内容
              </button>&nbsp;&nbsp;&nbsp;
              <button v-on:click="openSortModal(course)" class="btn btn-xs btn-primary">
                <i class="ace-icon fa fa-level-up bigger-120"></i>排序
              </button>&nbsp;&nbsp;&nbsp;
              <button v-on:click="edit(course)" class="btn btn-xs btn-info">
                <i class="ace-icon fa fa-pencil bigger-120"></i>编辑
              </button>&nbsp;&nbsp;&nbsp;
              <button v-on:click="del(course.id)" class="btn btn-xs btn-danger">
                <i class="ace-icon fa fa-trash-o bigger-120"></i>删除
              </button>
            </p>
          </div>
        </div>
      </div>
    </div>

    <!--课程模态框-->
    <div class="modal fade" id="myFormModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">表单</h4>
          </div>
          <div class="modal-body">
            <!--表格-->
            <form class="form-horizontal">

              <div class="form-group">
                <label class="col-sm-2 control-label">分类</label>
                <div class="col-sm-10">
                  <ul id="tree" class="ztree"></ul>
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">封面</label>
                <div class="col-sm-10">
                  <big-file v-bind:suffixs=" [ 'jpg','png','jpeg' ] "
                        v-bind:use="FILE_USE.COURSE.key"
                        v-bind:text="'上传封面'"
                        v-bind:after-upload="afterUpload"
                        v-bind:input-id=" 'image-upload' "></big-file>
                  <div v-show="course.image" class="row">
                    <div class="col-md-6">
                      <img v-bind:src="course.image" class="img-responsive">
                    </div>
                  </div>
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">名称</label>
                <div class="col-sm-10">
                  <input v-model="course.name" class="form-control" placeholder="输入名称"/>
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">讲师</label>
                <div class="col-sm-10">
                  <select v-model="course.teacherId" class="form-control">
                    <option v-for="o in teachers" v-bind:value="o.id" :key="o.num">{{ o.name }}</option>
                  </select>
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">概述</label>
                <div class="col-sm-10">
                  <textarea v-model="course.summary" class="form-control" placeholder="输入概述"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">时长</label>
                <div class="col-sm-10">
                  <p class="form-control-static" >{{course.time | formatSecond}}</p>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">价格（元）</label>
                <div class="col-sm-10">
                  <input v-model="course.price" class="form-control" placeholder="输入价格（元）"/>
                </div>
              </div>

              <div class="form-group">
                <label class="col-sm-2 control-label">级别</label>
                <div class="col-sm-10">
                  <select v-model="course.level" class="form-control">
                    <option v-for="o in COURSE_LEVEL" v-bind:value="o.key" :key="o.num">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">收费</label>
                <div class="col-sm-10">
                  <select v-model="course.charge" class="form-control">
                    <option v-for="o in COURSE_CHARGE" v-bind:value="o.key" :key="o.num">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">状态</label>
                <div class="col-sm-10">
                  <select v-model="course.status" class="form-control">
                    <option v-for="o in COURSE_STATUS" v-bind:value="o.key" :key="o.num">{{o.value}}</option>
                  </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">报名数</label>
                <div class="col-sm-10">
                  <input v-model="course.enroll" class="form-control" placeholder="输入报名数"/>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">顺序</label>
                <div class="col-sm-10">
                  <input v-model="course.sort" class="form-control" placeholder="输入顺序" disabled/>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" v-on:click="save()">保存</button>
          </div>
        </div><!-- /.modal-content-->
      </div><!-- /.modal-dialog-->
    </div><!-- /.modal-->

    <!--课程排序模态框-->
    <div class="modal fade" id="mySortModal" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="mySortModalLabel">编辑课程排序</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="control-label col-lg-3">
                  当前排序
                </label>
                <div class="col-lg-9">
                  <input class="form-control" v-model="sort.oldSort" name="oldSort" disabled/>
                </div>
              </div>
              <div class="form-group">
                <label class="control-label col-lg-3">
                  新排序
                </label>
                <div class="col-lg-9">
                  <input class="form-control" v-model="sort.newSort" name="newSort" placeholder="请输入新的排序"/>
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" v-on:click="updateSort()">更新排序</button>
          </div>
        </div><!-- /.modal-content-->
      </div><!-- /.modal-dialog-->
    </div><!-- /.modal-->
  </div>
</template>
<script>
import Pagination from "../../components/paginations";
import BigFile from "../../components/big-file";

export default {
  name: 'business-course',
  components: {BigFile, Pagination},
  data: function (){
    return {
      //映射表单数据
      course: {},
      courses: [],
      saveContentLabel: "",
      categorys: [],
      COURSE_LEVEL: COURSE_LEVEL,
      COURSE_CHARGE: COURSE_CHARGE,
      COURSE_STATUS: COURSE_STATUS,
      FILE_USE:FILE_USE,
      tree: {},
      sort: {
        id: "",
        oldSort: 0,
        newSort: 0,
      },
      teachers: [],
    }
  },
  mounted:function (){
    let _this = this;
    // _this.initTree();
    _this.allCategory();
    _this.allTeacher();

    _this.list(1);
    _this.$parent.activeSidebar("business-course-sidebar");
  },
  methods:{

    add() {
      let _this = this;
      _this.course = {
        sort: _this.$refs.pagination.total + 1
      };

      _this.tree.checkAllNodes(false);
      $("#myFormModal").modal("show");
    },

    edit(course) {
      let _this = this;
      _this.listCategory(course.id);
      _this.course = $.extend({}, course);
      $("#myFormModal").modal("show");
    },
    /**查询*/
    list(page){
      let _this = this;
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/list', {
        page: page,
        size: _this.$refs.pagination.size,
      }).then((response)=>{
        Loading.hide();
        console.log("查询课程列表结果：",response);
        let resp = response.data;
        _this.courses = resp.content.list;
        _this.$refs.pagination.render(page,resp.content.total);
      })
    },
    /**保存*/
    save(){
      let _this = this;
      /**保存校验*/
      if(1 != 1
      || !Validator.require(_this.course.name,"名称")
      || !Validator.length(_this.course.name,"名称",1,50)
      || !Validator.length(_this.course.summary,"概述",1,2000)
      || !Validator.require(_this.course.price,"价格（元）")
      || !Validator.length(_this.course.image,"封面",1,100)
      || !Validator.require(_this.course.level,"级别")
      ){
        return;
      }

      let categorys = _this.tree.getCheckedNodes();
      if (Tool.isEmpty(categorys)) {
        toast.warning("课程分类不能为空！");
        return;
      }
      _this.course.categorys = categorys;

      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/save',_this.course)
      .then((response)=>{
        console.log("保存课程列表结果：",response);
        let resp = response.data;
        if(resp.success){
          $("#myFormModal").modal("hide");
          _this.list(1);
          toast.success("保存成功！");
        }else{
          toast.warning(resp.message);
        }


      })
    },
    /**删除*/
    del(id){
      let _this = this;
      //弹出框
      Confirm.show("删除课程后不可恢复，您是否检查删除!",function (){
        _this.$ajax.delete(process.env.VUE_APP_SERVER + '/business/admin/course/delete/'+ id )
            .then((response)=>{
              console.log("删除课程列表结果：",response);
              let resp = response.data;
              if(resp.success){
                _this.list(1);
                toast.success("删除成功！");
              }
            });
      })
    },
    /**进入大章界面*/
    toChapter(course){
      let _this = this;
      SessionStorage.set(SESSION_KEY_COURSE, course);
      _this.$router.push("/business/chapter")
    },

    /**进入课程类容页面*/
    toContent(course){
      let _this = this;
      SessionStorage.set(SESSION_KEY_COURSE,course);
      _this.$router.push("/business/content")

    },
    /**查询 所有分类信息*/
    allCategory(){
      let _this = this;
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/category/all').then((response)=>{
        Loading.hide();
        let resp = response.data;
        _this.categorys = resp.content;
        _this.initTree();
      })
    },

    /**分类 树*/
    initTree(){
      let _this = this;
      let setting ={
        check:{
          enable:true
        },
        data:{
          simpleData:{
            idKey:"id",
            pIdKey:"parent",
            rootPId: "00000000",
            enable: true
          }
        }
      };

      let zNodes = _this.categorys;

      _this.tree = $.fn.zTree.init($("#tree"), setting, zNodes);

      //展开所有节点
      //_this.tree.expandAll(true);

    },
    /**根据课程id，查询所有分类*/
    listCategory(courseId) {
      let _this = this;
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/list-category/' + courseId).then((response) => {
        Loading.hide();
        let resp = response.data;
        let categorys = resp.content;

        _this.tree.checkAllNodes(false);
        for (let i = 0; i < categorys.length; i++) {
          let node = _this.tree.getNodeByParam("id", categorys[i].categoryId)
          _this.tree.checkNode(node, true);
        }
      });
    },

    /**保存课程内容*/
    saveContent() {
      let _this = this;
      let content = $("#content").summernote("code");
      Loading.show();
      // console.log("id:"+_this.course.id);
      // console.log("content:"+content);
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/save-content', {
        id: _this.course.id,
        content: content,
      }).then((response) => {
        Loading.hide();
        let resp = response.data;
        if (resp.success) {
          _this.saveContentLabel = "最后保存时间：" + Tool.dateFormat("hh时mm分ss秒");
          // toast.success("内容保存成功！");

        } else {
          toast.warning(resp.message);
        }
      });
    },
    /**课程排序模态框打开*/
    openSortModal(course) {
      let _this = this;
      _this.sort = {
        id: course.id,
        oldSort: course.sort,
        newSort: course.sort,
      }
      $("#mySortModal").modal("show");
    },
    /**课程排序*/
    updateSort() {
      let _this = this;
      if (_this.sort.newSort === _this.sort.oldSort) {
        toast.warning("排序没有变化！");
        return;
      }
      if (_this.sort.newSort <= 0 || _this.sort.newSort > _this.$refs.pagination.total) {
        toast.warning("请输入正确的排序值！(1至" + _this.$refs.pagination.total + ")");
        return;
      }
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/course/sort', _this.sort).then((response) => {
        let resp = response.data;

        if (resp.success) {
          Loading.hide();
          toast.success("更新排序成功！");
          $("#mySortModal").modal("hide");
          _this.list(1);
        } else {
          toast.error("更新排序失败!");
        }
      });
    },

    /**查询 所有教师信息*/
    allTeacher() {
      let _this = this;
      Loading.show();
      _this.$ajax.post(process.env.VUE_APP_SERVER + '/business/admin/teacher/all').then((response) => {
        Loading.hide();
        let resp = response.data;
        _this.teachers = resp.content;
      })
    },
    /**上传图片组件执行后回调函数*/
    afterUpload(resp) {
      let _this = this;
      let image = resp.content.path;
      _this.course.image = image;
    },

  }
}
</script>

<style scoped>
.caption h3 {
  font-size: 20px;
}

@media (max-width: 1199px) {
  .caption h3 {
    font-size: 16px;
  }
}
</style>